package shizhan.proxy;

import shizhan.exception.ValidationException;
import shizhan.pojo.Validate;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

public class ValidationInvocationHandler implements InvocationHandler {
    private Object target;

    public ValidationInvocationHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 获取接口上的方法信息
        Method[] methods = target.getClass().getInterfaces()[0].getMethods();
        for (Method method1 : methods) {
            if (method1.getName().equals(method.getName()) && method1.getParameterCount() == args.length) {
                Parameter[] parameters = method1.getParameters();
                for (int i = 0; i < parameters.length; i++) {
                    if (parameters[i].isAnnotationPresent(Validate.class)) {
                        Validate validate = parameters[i].getAnnotation(Validate.class);
                        Object arg = args[i];
                        if (arg instanceof Double) {
                            Double d = (Double) arg;
                            if (validate.notEmpty() && d == null) {
                                throw new ValidationException("Parameter cannot be null");
                            }
                            if (!Double.isInfinite(validate.minValue())
                                    && d < validate.minValue()) {
                                throw new ValidationException("Parameter value is" +
                                        " too low " + d);
                            }
                            if (!Double.isInfinite(validate.maxValue())
                                    && d > validate.maxValue()) {
                                throw new ValidationException("Parameter value is too high: " + d);
                            }
                        } else {
                            throw new IllegalArgumentException("Unsupportedparameter type:" + arg.getClass().getName());
                        }
                    }
                }

            }

        }
        return method.invoke(target, args);
    }

}
